<?php

namespace App\Http\Controllers;

use App\models\Cate;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class CateController extends Controller
{
    public $list = []; //定义一个空数组用于存储格式化后的

    public function cateList()
    {

        $cates = Cate::orderBy('sort','desc')->get()->toArray();
        $tree = $this->getTree($cates);

        foreach ($tree as $k=>$v){
            if ($v['level'] == 0){
                $tree[$k]['lay_icon_open'] = "/img/1_open.png";
                $tree[$k]['lay_icon_close'] = "/img/1_close.png";
            }else{
                $tree[$k]['lay_icon'] = "/img/4.png";
            }
        }

        return $this->list($tree);
    }

    public function destroy(Request $request)
    {
        $children = $request->input('children');
        if ($children){
            return $this->err('该分类存在下级节点无法删除！');
        }
        $cate = Cate::find($request->input('id'));
        if ($cate->delete()){
            return $this->ok('删除成功');
        }
    }

    public function getTree($data,$pid=0,$level=0)
    {
        foreach ($data as $k=>$v){
            if ($v['parent_id'] == $pid){
                $v['level'] = $level;
                $this->list[] = $v;
                $this->getTree($data,$v['id'],$level+1);
            }
        }
        return $this->list;
    }

    public function createTop(Request $request)
    {
        $cate = new Cate();
        $cate->name = $request->input('name');
        $cate->parent_id = 0;
        $cate->sort = 0;
        $cate->visibility = 1;

        if ($cate->save()){
            return $this->ok('添加成功');
        }
    }

    public function createSon(Request $request)
    {
        $cate = new Cate();
        $cate->name = $request->input('sonname');
        $cate->parent_id = $request->input('id');
        $cate->sort = 0;
        $cate->visibility = 1;

        if ($cate->save()){
            return $this->ok('添加成功');
        }
    }

    public function update(Request $request)
    {
//        dd($request->input());
        $sort = $request->input('sort');

        if (!is_numeric($sort)){
            return $this->err('排序值只能是数字');
        }

        $cate = Cate::find($request->input('id'));
        $cate->name = $request->input('name');
        $cate->sort = $sort;


        if ($cate->save()){
            return $this->ok('修改成功');
        }
    }
}
